<?php

/**
 * 授权控制器
 */
namespace Custom\Controller;
use Think\Controller;

class AccreditController extends UserController {

    function __construct()
    {
        parent::__construct();
        $this->M_Sum = M('Sum_view');
        $this->M_View = M('View_name');

        $find = M("Accesstoken")->find();
        if($info['expiresin'] < strtotime("-30 minutes")){
            $file = __ROOT__.'WXlog/ticket.log';
            $fp = @fopen($file,'r');
            $line = fgets($fp, 1024);
            /*令牌获取*/
            $data = '{"component_appid":"'.C('appid').'", "component_appsecret":"'.C('appsecret').'", "component_verify_ticket":"'.$line.'"}';
            $response = $this->mycurl('https://api.weixin.qq.com/cgi-bin/component/api_component_token',$data,1);
            $response = json_decode($response,true);
            M("Accesstoken")->where("id = 1")->save(array("accesstoken"=>$response['component_access_token'],"expiresin"=>$response['expires_in']+time()));
            $this->accesstoken = $response['component_access_token'];
            $this->expiresin = $response['expires_in']+time();
        }else{
            $this->accesstoken = $find['accesstoken'];
            $this->expiresin = $find['expiresin'];
        }
        /*//if(!session('accesstoken')||session('expiresin')<strtotime("-30 minutes")){
        $file = __ROOT__.'WXlog/ticket.log';
        $fp = @fopen($file,'r');
        $line = fgets($fp, 1024);
        $data = '{"component_appid":"'.C('appid').'", "component_appsecret":"'.C('appsecret').'", "component_verify_ticket":"'.$line.'"}';
        $response = $this->mycurl('https://api.weixin.qq.com/cgi-bin/component/api_component_token',$data,1);
        $response = json_decode($response,true);
        session('accesstoken',$response['component_access_token']);
        session('expiresin',$response['expires_in']+time());
        //}*/
    }


    public function index(){
        /*预授权码获取*/
        $data = '{"component_appid":"'.C('appid').'"}';
        $response = $this->mycurl('https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$this->accesstoken,$data,1);
        $response = json_decode($response,true);
        $preauthcode = $response['pre_auth_code'];
        $expiresin = $response['expires_in']+time();
        /*授权页网址*/
        $uri = urlencode("https://commission.weiyuekj.com/Custom/Accredit/redirurl");
        /*传输数据*/
        $this->assign('buttonurl','https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.C('appid').'&pre_auth_code='.$preauthcode.'&redirect_uri='.$uri);
        /*读取内容*/
        $info = M('Accredit')->where('c_id = '.$this->c_id)->find();
        $this->assign('info',$info);
        if($info) $this->autacst();
        $this->display();
    }


    //回调获取信息
    public function redirurl(){
        /*回调授权码*/
        $authcode = I('get.auth_code');
        $expiresin = I('expires_in')+time();
        /*小判断*/
        if(!$authcode) die($this->redirect('Index/index'));
        else{
            /*获取授权信息*/
            $data1 = '{"component_appid":"'.C('appid').'", "authorization_code":"'.$authcode.'"}';
            $response1 = $this->mycurl('https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$this->accesstoken,$data1,1);
            $response1 = json_decode($response1,true);
            $author_aid = $response1['authorization_info']['authorizer_appid'];
            $author_tok = $response1['authorization_info']['authorizer_access_token'];/*失效可用authorizer_refresh_token再获取*/
            $author_exp = $response1['authorization_info']['expires_in']+time();
            $author_ref = $response1['authorization_info']['authorizer_refresh_token'];/*保留*/
            session('authortok',$author_tok);/*2小时后失效*/
            session('authorexp',$author_exp);/*2小时后失效*/
            /*获取授权方基本信息*/
            $data2 = '{"component_appid":"'.C('appid').'", "authorizer_appid":"'.$author_aid.'"}';
            $response2 = $this->mycurl('https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token='.$this->accesstoken,$data2,1);
            $response2 = json_decode($response2,true);
            /*判断小程序*/
            if($response2['authorizer_info']['MiniProgramInfo']){
                $message['c_id'] = $this->c_id;
                $message['authorizer_appid'] = $response2['authorization_info']['authorizer_appid'];
                $message['nick_name'] = $response2['authorizer_info']['nick_name'];
                $message['principal_name'] = $response2['authorizer_info']['principal_name'];
                $message['user_name'] = $response2['authorizer_info']['user_name'];
                $message['authorizer_refresh_token'] = $response2['authorization_info']['authorizer_refresh_token'];/*保留*/
                $message['verify_type_info'] = $response2['authorizer_info']['verify_type_info']['id'];
                $message['signature'] = $response2['authorizer_info']['signature'];
                $message['head_img'] = $response2['authorizer_info']['head_img'];
                $message['qrcode_url'] = $response2['authorizer_info']['qrcode_url'];
                $message['network'] = serialize($response2['authorizer_info']['network']);
                $message['func_info'] = serialize($response2['authorization_info']['func_info']);
                $message['authcode'] = $authcode;
                $message['addtime'] = time();
                $message['state'] = 1;
                $info = M('Accredit')->where('c_id = '.$this->c_id)->find();
                if($info) M('Accredit')->where('c_id = '.$this->c_id)->delete();
                M('Accredit')->where("authorizer_appid = '".$message['authorizer_appid']."'")->save(array("state"=>0));
                if(M('Accredit')->add($message)){
                    $data3 = '{"action":"set","requestdomain":["https:\/\/'.C('url').'"],"wsrequestdomain":["wss:\/\/'.C('url').'"],"uploaddomain":["https:\/\/'.C('url').'"],"downloaddomain":["https:\/\/'.C('url').'"]}';
                    $response3 = $this->mycurl('https://api.weixin.qq.com/wxa/modify_domain?access_token='.session('authortok'),$data3,1);
                    die($this->redirect('Accredit/index'));
                    die($this->success(L('shouquancg'),U('Accredit/index')));
                }else{
                    die($this->error(L('preshouquan'),U('Accredit/index')));
                }
            }else{
                die($this->error(L('shouquansb'),U('Accredit/index')));
            }
        }
    }


    //管理小程序
    public function manager(){
        $temp = M('Accredit')->where('c_id = '.$this->c_id)->find();
        if(!$temp) die($this->redirect('Accredit/index'));
        else $this->autacst();
        /****/
        $list_fb = M('Accrtemplate')->where('acc_id = '.$temp['acc_id'].' and state = 2')->select();
        $this->assign('list_fb',$list_fb);
        /****/
        $list_sh = M('Accrtemplate')->where('acc_id = '.$temp['acc_id'].' and state = 1')->select();
        if($list_sh){
            $data = '{"auditid":'.$list_sh[0]['auditid'].'}';
            $response_sh = $this->mycurl('https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token='.session('authortok'));
            $response_sh = json_decode($response_sh,true);

            if($response_sh['errmsg']=='ok'&&$response_sh['status']==0){
                $list_sh[0]['reason'] = "可发布";
                $list_sh[0]['status'] = 1;
            }else if($response_sh['status']==1){
                $list_sh[0]['reason'] = $response_sh['reason']."<font style='color:red'>（请重新编辑后上传）</font>";
                $list_sh[0]['status'] = 1;
            }else if($response_sh['status']==2){
                $list_sh[0]['reason'] = "审核中";
            }

            $response_sc = $this->mycurl('https://api.weixin.qq.com/wxa/get_qrcode?access_token='.session('authortok'));
            $response_sc = base64_encode($response_sc);
            $list_sh[0]['mypic'] = "data:image/png;base64,".$response_sc;
        }
        $this->assign('list_sh',$list_sh);
        /****/
        $list_sc = M('Accrtemplate')->where('acc_id = '.$temp['acc_id'].' and state = 0')->select();
        if($list_sc){
            $response_sc = $this->mycurl('https://api.weixin.qq.com/wxa/get_qrcode?access_token='.session('authortok'));
            $response_sc = base64_encode($response_sc);
            $list_sc[0]['mypic'] = "data:image/png;base64,".$response_sc;
        }
        $this->assign('list_sc',$list_sc);
        $this->display();
    }


      //添加编辑小程序
      public function manager_add(){
        $temp = M('Accredit')->where('c_id = '.$this->c_id)->find();
        if(!$temp){die($this->redirect('Accredit/index'));}
        $id = I('get.id',0,'intval');
         $sid = session('s_id');
         if(!$sid){
            $this->error('请选择门店');
         }
         $style = M('store_style')->where('s_id='.$sid)->find();

        if(IS_POST){
            // v($_POST);
            $save['template_id'] = I('post.template_id',0,'intval');
            $template = M('Template')->where("templateid = ".$save['template_id'])->find();
            // $save['user_version'] = $template['temp_version'];

            //改变样式
            /*************************************************************************************************/
            $styleData = array(
                'title' => I('title'), 
                'title_bg' => I('title_bg'), 
                'title_color' => I('title_color'), 
                'store_bg' => I('store_bg'), 
                'store_name_color' => I('store_name_color'), 
                );

            if($style){
                M('store_style')->where('s_id='.$sid)->save($styleData);
            }else{
                $styleData['s_id'] = $sid;
                M('store_style')->add($styleData);
            }


            // if(I('post.listpp0','','trim')){
            //     $barlist[0]['pagePath'] = I('post.listpp0','','trim');
            //     $barlist[0]['text'] = I('post.listt0','','trim');
            //     //$barlist[0]['iconPath'] = "images/icon/home.png";
            //     //$barlist[0]['selectedIconPath'] = "images/icon/home_fill.png";
            // }
            // if(I('post.listpp1','','trim')){
            //     $barlist[1]['pagePath'] = I('post.listpp1','','trim');
            //     $barlist[1]['text'] = I('post.listt1','','trim');
            // }
            // if(I('post.listpp2','','trim')){
            //     $barlist[2]['pagePath'] = I('post.listpp2','','trim');
            //     $barlist[2]['text'] = I('post.listt2','','trim');
            // }
            // if(I('post.listpp3','','trim')){
            //     $barlist[3]['pagePath'] = I('post.listpp3','','trim');
            //     $barlist[3]['text'] = I('post.listt3','','trim');
            // }
            // if(I('post.listpp4','','trim')){
            //     $barlist[4]['pagePath'] = I('post.listpp4','','trim');
            //     $barlist[4]['text'] = I('post.listt4','','trim');
            // }

            // $extjson['extAppid'] = $temp['authorizer_appid'];
            // $extjson['ext'] = array("cid"=>$this->c_id);
            // $extjson['window'] = array("navigationBarBackgroundColor"=>I('post.titleback'),"navigationBarTitleText"=>I('post.titletext'),"navigationBarTextStyle"=>I('post.titlecolor'));
            /*************************************************************************************************/

            $extjson['tabBar'] = array("selectedColor"=>I('post.barclick'),"color"=>I('post.barcolor'),"list"=>$barlist);
            $extjson = json_encode($extjson,JSON_UNESCAPED_UNICODE);

            $data['template_id'] = $save['template_id'];
            $data['ext_json'] = $extjson;
            $data['user_version'] = $save['user_version'];
            $data = json_encode($data,JSON_UNESCAPED_UNICODE);

            $response = $this->mycurl('https://api.weixin.qq.com/wxa/commit?access_token='.session('authortok'),$data,1);
            $response = json_decode($response,true);
            if($response['errmsg']=='ok'){
                $save['ext_json'] = $extjson;
                if($id){
                    $save['add_time'] = time();
                    $result = M('Accrtemplate')->where('id = '.$id)->save($save);
                }else{
                    $save['c_id'] = $this->c_id;
                    $save['add_time'] = time();
                    $save['acc_id'] = $temp['acc_id'];
                    $result = M('Accrtemplate')->add($save);
                }
                $this->success('操作成功',U('Accredit/manager'));
            }
            else $this->error('操作失败'.$response['errmsg']);
        }else{
            $this->templateid = M('Template')->order("templateid asc")->select();
            if($id){
                $info = M('Accrtemplate')->find($id);
                $info['ext_json'] = json_decode($info['ext_json'],TRUE);
                $this->assign('info',$info);
            }
             $this->assign('style',$style);
            $this->display();
        }
    }


    //审核小程序
    public function manager_sh(){
        $temp = M('Accredit')->where('c_id = '.$this->c_id)->find();
        if(!$temp){die($this->redirect('Accredit/index'));}
        $id = I('get.id',0,'intval');

        if($id){
            $response1 = $this->mycurl('https://api.weixin.qq.com/wxa/get_category?access_token='.session('authortok'));
            $response1 = json_decode($response1,true);
            
            $response2 = $this->mycurl('https://api.weixin.qq.com/wxa/get_page?access_token='.session('authortok'));
            $response2 = json_decode($response2,true);

            for($i=0; $i<count($response2['page_list']); $i++){
                $data['item_list'][$i]['address'] = $response2['page_list'][$i];
                $data['item_list'][$i]['tag'] = $response1['category_list'][0]['first_class']." ".$response1['category_list'][0]['second_class']." ".$response1['category_list'][0]['third_id'];
                switch($response2['page_list'][$i]){
                    case 'pages/about/about':
                    $data['item_list'][$i]['title'] = "关于";break;
                    case 'pages/contact/contact':
                    $data['item_list'][$i]['title'] = "联系";break;
                    case 'pages/detail/detail':
                    $data['item_list'][$i]['title'] = "详情";break;
                    case 'pages/index/index':
                    $data['item_list'][$i]['title'] = "首页";break;
                    case 'pages/lists/lists':
                    $data['item_list'][$i]['title'] = "列表";break;
                    default:break;
                }
                if($response1['category_list'][0]['first_class']){
                    $data['item_list'][$i]['first_class'] = $response1['category_list'][0]['first_class'];
                    $data['item_list'][$i]['first_id'] = $response1['category_list'][0]['first_id'];
                }
                if($response1['category_list'][0]['second_class']){
                    $data['item_list'][$i]['second_class'] = $response1['category_list'][0]['second_class'];
                    $data['item_list'][$i]['second_id'] = $response1['category_list'][0]['second_id'];
                }
                if($response1['category_list'][0]['third_class']){
                    $data['item_list'][$i]['third_class'] = $response1['category_list'][0]['third_class'];
                    $data['item_list'][$i]['third_id'] = $response1['category_list'][0]['third_id'];
                }
            }
            $data = json_encode($data,JSON_UNESCAPED_UNICODE);
            $response = $this->mycurl('https://api.weixin.qq.com/wxa/submit_audit?access_token='.session('authortok'),$data,1);
            $response = json_decode($response,true);

            if($response['errmsg']=='ok'){
                M('Accrtemplate')->where('id = '.$id)->save(array('state'=>1,'auditid'=>$response['auditid']));
                $this->success('上传成功',U('Accredit/manager'));
            }else{
                $this->error('上传失败');
            }
        }
    }


    //发布小程序
    public function manager_fb(){
        $temp = M('Accredit')->where('c_id = '.$this->c_id)->find();
        if(!$temp){die($this->redirect('Accredit/index'));}
        $id = I('get.id',0,'intval');
        if($id){
            $response = $this->mycurl('https://api.weixin.qq.com/wxa/release?access_token='.session('authortok'),'{}',1);
            $response = json_decode($response,true);
            if($response['errmsg']=='ok'){
                M('Accrtemplate')->where('id = '.$id)->save(array('state'=>2));
                $this->success('发布成功',U('Accredit/manager'));
            }else{
                $this->error($response['errmsg']);
            }
        }
    }


    //删除小程序模板
    public function manager_del(){
        if(IS_AJAX){
            $id = I('get.id',0,'intval');
            $info = M('Accrtemplate')->find($id);
            if($info){
                M('Accrtemplate')->where('id = '.$id)->delete();
                $this->ajaxReturn(array('result'=>'yes'));
            }
        }
    }


    //绑定体验者
    public function adminer(){
        $this->autacst();
        $temp = M('Accredit')->where('c_id = '.$this->c_id)->find();
        if(!$temp){die($this->redirect('Accredit/index'));}
        if(IS_AJAX){
            $wechatid = I('get.wechatid','','trim');
            if($wechatid){
                $data = '{"wechatid":"'.$wechatid.'"}';
                $response = $this->mycurl('https://api.weixin.qq.com/wxa/bind_tester?access_token='.session('authortok'),$data,1);
                $response = json_decode($response,true);
                // var_dump($response);
                if($response['errcode']==0 && $response['errmsg']=='ok'){
                    $message['c_id'] = $this->c_id;
                    $message['acc_id'] = $temp['acc_id'];
                    $message['wechatid'] = $wechatid;
                    $message['addtime'] = time();
                    M('Accradmin')->add($message);
                    $this->ajaxReturn(array('result'=>'ok'));
                }else if($response['errcode']==85001){
                    $this->ajaxReturn(array('result'=>'微信号不存在或微信号设置为不可搜索'));
                }else if($response['errcode']==85002){
                    $this->ajaxReturn(array('result'=>'小程序绑定的体验者数量达到上限'));
                }else if($response['errcode']==85003){
                    $this->ajaxReturn(array('result'=>'微信号绑定的小程序体验者达到上限'));
                }else if($response['errcode']==85004){
                    if(M('Accradmin')->where('acc_id = '.$temp['acc_id'].' and wechatid = "'.$wechatid.'"')->find()){
                        $this->ajaxReturn(array('result'=>'微信号已经绑定'));
                    }else{
                        $message['c_id'] = $this->c_id;
                        $message['acc_id'] = $temp['acc_id'];
                        $message['wechatid'] = $wechatid;
                        $message['addtime'] = time();
                        M('Accradmin')->add($message);
                        $this->ajaxReturn(array('result'=>'ok'));
                    }
                }else{
                    $this->ajaxReturn(array('result'=>'系统繁忙'));
                }
            }
        }else{
            $info = M('Accradmin')->where('acc_id = '.$temp['acc_id'])->select();
            $this->assign('info',$info);
            $this->display();
        }
    }


    //删除体验者
    public function adminer_del(){
        if(IS_AJAX){
            $id = I('get.id',0,'intval');
            $info = M('Accradmin')->where('accradmin_id = '.$id)->find();
            $wechatid = $info['wechatid'];
            if($wechatid){
                $data = '{"wechatid":"'.$wechatid.'"}';
                $response = $this->mycurl('https://api.weixin.qq.com/wxa/unbind_tester?access_token='.session('authortok'),$data,1);
                $response = json_decode($response,true);
                if($response['errcode']==0 && $response['errmsg']=='ok'){
                    M('Accradmin')->where('accradmin_id = '.$id)->delete();
                    $this->ajaxReturn(array('result'=>'ok'));
                }else{
                    $this->ajaxReturn(array('result'=>'系统繁忙'));
                }
            }
        }
    }


    //获取authorizer_access_token
    protected function autacst(){
        if(!session('authortok')||session('authorexp')<time()){
            $info = M('Accredit')->where('c_id = '.$this->c_id)->find();
            if($info){
                $data = '{"component_appid":"'.C('appid').'", "authorizer_appid":"'.$info['authorizer_appid'].'", "authorizer_refresh_token":"'.$info['authorizer_refresh_token'].'"}';
                $response = $this->mycurl('https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$this->accesstoken,$data,1);
                $response = json_decode($response,true); 
                /*******************************************************/
                //暂时用来做判断
                if($response['errcode']==61003&&$info['state']==1){
                    M('Accredit')->where('c_id = '.$this->c_id)->save(array('state'=>0));
                }
                else{
                    session('authortok',$response['authorizer_access_token']);
                    session('authorexp',$response['expires_in']+time());
                }
                /*******************************************************/
                //session('authortok',$response['authorizer_access_token']);
                //session('authorexp',$response['expires_in']+time());
            }
        }
    }


    protected function mycurl($url, $arrays=false, $is_post=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if($is_post){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arrays);
            curl_setopt($ch, CURLOPT_URL, $url);
        }
        else{
            if($arrays){
                curl_setopt($ch, CURLOPT_URL, $url.'?'.$arrays );
            }else{
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if($response === FALSE){
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

}